#!/usr/bin/env python3
import argparse, os, yaml

from strange_io.pixels import StrangePixels
from strange_io.colors import StrangeColors

#region args
parser = argparse.ArgumentParser(prog='sPixels')
parser.add_argument('file_path', nargs='?')
parser.add_argument('--width', help='Set canvas width', type=int)
parser.add_argument('--height', help='Set canvas height', type=int)
parser.add_argument('--size', help='Set the size of the pixels on the canvas', type=int)
parser.add_argument('--palette', help='Path to Strange Colors document to use as the palette')
parser.add_argument('--export', help='Automate the task of exported Strange Pixels documents, and specify output path')
parser.add_argument('--config', help='Specify the path to the config file (Must be a YAML document)', default='config.yml')
args = parser.parse_args()
#endregion

if os.path.exists(args.config):
    with open(args.config) as f:
        config = yaml.safe_load(f.read())
else:
    config = {
        'canvas': {
            'pixel': {
                'size': 20,
                'border': {
                    'width': 2,
                    'color': [0, 0, 0]
                }
            },
            'brush': 'none'
        }
    }

def main():
    colors = StrangeColors()
    pixels = StrangePixels()
    if args.export:
        if args.file_path:
            if args.palette:
                if os.path.exists(args.file_path):
                    if os.path.exists(args.palette):
                        try:
                            pixels.load_file(args.file_path)
                            colors.load_file(args.palette)
                            img = pixels.export(colors, True)
                            img.save(args.export)
                            print('Exported:', args.file_path)
                        except ValueError as e:
                            print('ValueError:', str(e))
                        except TypeError as e:
                            print('TypeError:', str(e))
                    else:
                        print('Strange Colors docuement not found')
                else:
                    print('Strange Pixels docuement not found')
            else:
                print('Strange Colors docuement not specified')
        else:
            print('Strange Pixels docuement not specified')
    else:
        from app import MainApplication
        from editor import PixelsEditor

        app = MainApplication(args, config)

        if not args.file_path:
            app.show_gui(PixelsEditor)

        app.mainloop()

if __name__ == '__main__':
    main()
